package com.beagle.njddapp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.IBinder;
import android.text.InputType;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.beagle.njddapp.R;
import com.beagle.njddapp.base.BaseApplication;
import com.beagle.njddapp.base.BaseMvpActivity;
import com.beagle.njddapp.core.UserService;
import com.beagle.njddapp.ui.presenter.LoginPresenter;
import com.beagle.njddapp.ui.view.LoginView;
import com.beagle.njddapp.utils.CountDownUtil;
import com.beagle.njddapp.utils.PatternUtil;
import com.beagle.njddapp.utils.PrefsManager;
import com.beagle.njddapp.utils.StatusBarUtil;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;

import butterknife.BindView;
import butterknife.OnClick;

import static com.beagle.njddapp.core.UserService.PHONE;

/**
 * @author hxx
 * @date 2021-03-02 22:31
 * 登录
 */
public class PasswordLoginActivity extends BaseMvpActivity<LoginView, LoginPresenter> implements LoginView {

    @BindView(R.id.ed_phone)
    EditText edPhone;
    @BindView(R.id.ed_msg)
    EditText edMsg;
    @BindView(R.id.tv_smg)
    TextView tvMsg;
    @BindView(R.id.protocolCheckBox)
    ImageView mProtocolCheckBoxIv;
    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.prograssBar)
    ProgressBar progressBar;
    private CountDownUtil mCountDownUtil;
    private static final int COUNT_DOWN = 60;
    private boolean isProtocolChecked;
    private boolean close=true;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login_password;
    }

    @Override
    public void init() {
        StatusBarUtil.immersive(this, Color.WHITE);
        StatusBarUtil.darkMode(this);
        edPhone.setText(UserService.getInstance().getPhone());
    }

    @Override
    public LoginView getMvpView() {
        return this;
    }

    @Override
    public LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    public void onError(String message) {
        progressBar.setVisibility(View.GONE);

        ToastUtils.showShort(message);
    }

    @OnClick({R.id.tv_smg,R.id.tv_login,R.id.iv_login_wechat,R.id.tv1,R.id.tv2,R.id.protocolCheckBox,R.id.tv_reigster,R.id.iv_close,R.id.tv_forget})
    public void onCLick(View view){
        switch (view.getId()){
            case R.id.protocolCheckBox :
                isProtocolChecked = !mProtocolCheckBoxIv.isSelected();
                mProtocolCheckBoxIv.setSelected(isProtocolChecked);
                break;
            case R.id.tv_reigster:
                startActivity(new Intent(this,RegisterActivity.class));
                break;
            case R.id.tv_forget:
                startActivity(new Intent(this,FindPasswordActivity.class));
                break;
            case R.id.tv_smg:
                String phoneNumber = edPhone.getText().toString().trim();
                if (!PatternUtil.isMobile(phoneNumber)) {
                    ToastUtils.showShort("请输入正确的手机号");
                    return;
                }
                startCountDown();
//                presenter.getMsg(phoneNumber);
                break;
            case R.id.tv_login:
                if (!isProtocolChecked){
                    ToastUtils.showShort("请查看并同意《用户协议》与《隐私协议》");
                    return;
                }
                if (TextUtils.isEmpty(edPhone.getText().toString())||!PatternUtil.isMobile(edPhone.getText().toString())){
                    ToastUtils.showShort("请输入正确的手机号");
                    return;
                }
                if (TextUtils.isEmpty(edMsg.getText().toString())){
                    ToastUtils.showShort("请输入最少6位的登录密码");
                    return;
                }
                progressBar.setVisibility(View.VISIBLE);
                presenter.register(edPhone.getText().toString(),edMsg.getText().toString(),"login","");

                break;
            case R.id.iv_login_wechat:
                ToastUtils.showShort("功能即将开放");
                break;
            case R.id.tv1:
                startActivity(new Intent(this,WebActivity.class).putExtra("type",1).putExtra("url","https://api.sinagin.com/njdd/api/static/userAgreement"));
                break;
            case R.id.tv2:
                startActivity(new Intent(this,WebActivity.class).putExtra("type",2).putExtra("url","https://api.sinagin.com/njdd/api/static/privacyPolicy"));
                break;
            case R.id.iv_close:
                if (close){
                    close=false;
                    ivClose.setImageResource(R.mipmap.icon_eye);
                    edMsg.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    if (edMsg.getText().length()>0){
                        edMsg.setSelection(edMsg.getText().length());
                    }
                }else {
                    close=true;
                    ivClose.setImageResource(R.mipmap.icon_eye_close);
                    edMsg.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    if (edMsg.getText().length()>0){
                        edMsg.setSelection(edMsg.getText().length());
                    }
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountDownUtil != null) {
            mCountDownUtil.release();
        }
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }


    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
    /**
     * 获取InputMethodManager，隐藏软键盘
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    /**
     * 获取验证码倒计时
     */
    private void startCountDown() {
        if (mCountDownUtil == null) {
            mCountDownUtil = new CountDownUtil();
        }

        tvMsg.setEnabled(false);
        tvMsg.setTextColor(getResources().getColor(R.color.color_999999));

        mCountDownUtil.start(COUNT_DOWN, new CountDownUtil.CountDownCallback() {
            @Override
            public void countDown(int time) {
                Resources resources = BaseApplication.getInstance().getResources();
                String text = time > 0 ? String.format(resources.getString(R.string.code_countdown_time), String.valueOf(time)) : resources.getString(R.string.get_code_again);

                tvMsg.setText(text);
                if (time <= 0) {
                    tvMsg.setEnabled(true);
                    tvMsg.setTextColor(getResources().getColor(R.color.color_0D0D0D));
                    stopCountDown();
                }
            }
        });
    }

    private void stopCountDown() {
        if (mCountDownUtil != null) {
            mCountDownUtil.stop();
        }

        tvMsg.setEnabled(true);
        tvMsg.setTextColor(getResources().getColor(R.color.color_0D0D0D));
        tvMsg.setText(R.string.get_code_again);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        edPhone.setText(UserService.getInstance().getPhone());

    }
//    private boolean isFirst=true;

    @Override
    public void toMian() {
//        if (isFirst){
//            presenter.firstRequest();
//        }
//        isFirst=false;
        PrefsManager.getInstance(BaseApplication.getInstance()).putString(PHONE,edPhone.getText().toString());
        tvMsg.postDelayed(new Runnable() {
            @Override
            public void run() {
                progressBar.setVisibility(View.GONE);

                startActivity(new Intent(PasswordLoginActivity.this,MainActivity.class));
                finish();
            }
        },1000);
    }
    @Override
    public void toChooseRole() {
        PrefsManager.getInstance(BaseApplication.getInstance()).putString(PHONE,edPhone.getText().toString());
        tvMsg.postDelayed(new Runnable() {
            @Override
            public void run() {
                progressBar.setVisibility(View.GONE);

                startActivity(new Intent(PasswordLoginActivity.this,ChooseRoleActivity.class));
                finish();
            }
        },1000);
    }

    @Override
    public void toInfo() {
        PrefsManager.getInstance(BaseApplication.getInstance()).putString(PHONE,edPhone.getText().toString());
        tvMsg.postDelayed(new Runnable() {
            @Override
            public void run() {
                progressBar.setVisibility(View.GONE);

                startActivity(new Intent(PasswordLoginActivity.this,BasicUserInfoActivity.class));
                finish();
            }
        },1000);
    }
}
